<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Townprogram;
use app\admin\model\User as UserMdl;
use app\admin\model\Article;
use app\admin\model\Villages;
use app\admin\model\Image;
use app\admin\model\Member;
use app\admin\model\Povertymember;
use app\admin\model\Operator;
use app\admin\service\Dynamic as DynamicService;

use think\Db;
use think\Exception;

/**
 * 个人中心
 */
class User extends BaseController
{

    /**
     * 个人主页
     */
    public function getUserDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $userId = $param->userId;
        $where = [
            'userId' => $param->id
        ];

        // 个人信息
        $user = UserMdl::get($param->id);
        if(!$user){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到该用户');
        }
        //$member = Member::where(['id' => $user->memberId, 'isDelete' => 2])->find();
        $member = Member::where(['userId' => $user->id, 'isDelete' => 2])->find();
        if($member){
            $member = $this->getMemberInfo($member);

            $user['member'] = $member;

            $povertypolicys = $this->getPovertypolicys(['memberId' => $user->memberId], 0, 2);
            // 扶贫项目 // TODO 不能用 Povertyproject 表里的 aidingId（帮扶人）字段，因为贫困户的 aidingId 会发生改变
            //$povertys = $this->getPovertys(['a.aidingId' => $user->memberId], 0, 2);
            $memberIds = Povertymember::where(['aidingId' => $user->memberId])->column('memberId');
            $povertys = $this->getPovertys(['a.memberId' => ['in', $memberIds]], 0, 2);
        }

        // 主页
        // 农产品名片
        $productcards = $this->getProductcards($where, 0, 2);
        // 农场
        $farms = $this->getFarms($where, 0, 2);
        // 享受政策
        $povertypolicys = isset($povertypolicys) ? $povertypolicys : '';
        // 扶贫项目
        $povertys = isset($povertys) ? $povertys : '';

        // 困贫户查阅权限
        $townconfig = \app\admin\model\Townconfig::where('townId', $param->townId)->find();
        $viewPovertymember = $townconfig->isshowpinkun;
        if($townconfig->isshowpinkun != 1 && $param->id != $param->userId){
            $viewMemberIds = \app\admin\model\Showpinkunmember::where('townId', $param->townId)->field('memberId')->select();
            $viewMemberIds = array_column($viewMemberIds, 'memberId');

            if(!$member || !in_array($user->memberId, $viewMemberIds)){
                $povertypolicys = [];
                $povertys = [];
            }
        }

        // 最新信息
        //$dynamics = $this->getDynamics(['createUser' => $userId], $userId, 0, 2);

        $home = [
            'productcards' => $productcards,
            'farms' => $farms,
            'povertypolicys' => $povertypolicys,
            'povertys' => $povertys,
            //'dynamics' => $dynamics,
            'viewPovertymember' => $viewPovertymember
        ];

        $data = [
            'home' => $home ? : '',
            'information' => $user ? : '',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    // 获取农产品名片列表
    protected function getProductcards($where, $start, $length)
    {
        $model = new \app\admin\model\Userproductcard();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();

        return $result;
    }

    // 获取农场列表
    protected function getFarms($where, $start, $length)
    {
        $model = new \app\admin\model\Userfarm();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        if(!$result){
            return [];
        }

        foreach ($result as $item) {
            $item['villageName'] = \app\admin\model\Villages::where('id', $item['villageId'])->value('name');
            $item['croptypeName'] = \app\admin\model\Croptype::where('id', $item['croptypeId'])->value('name');
            $item['cropName'] = \app\admin\model\Crop::where('id', $item['cropId'])->value('name');
            $item['varietieName'] = \app\admin\model\Varieties::where('id', $item['varietieId'])->value('name');

            // 图片
            $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();
        }

        return $result;
    }

    // 获取享受政策列表
    protected function getPovertypolicys($where, $start, $length)
    {
        $model = new \app\admin\model\Povertypolicy();
        $fields = 'a.*, b.year';
        $order = 'b.year DESC';
        $result = $model->alias('a')->where($where)->join('povertypolicyledger b', 'a.policyledgerId = b.id')->field($fields)->limit($start, $length)->order($order)->select();
        if(!$result){
           return [];
        }

        foreach ($result as $item) {
            //$policyledgerInfo = \app\admin\model\Povertypolicyledger::where(['id' => $item['policyledgerId']])->find();
            // 享受政策年份
            //$item->year = $policyledgerInfo->year;
            $policyList = json_decode($item['policy'], true);
            // 享受政策（项）
            $item->countPovertypolicy = count($policyList);
            // 金额合计（元）
            $totalAmount = 0;
            foreach ($policyList as $policy) {
                if(count($policy['policySpec']) > 1){
                    // 多列
                    foreach($policy['policySpec'] as $policySpec){
                        if($policySpec['explain'] == 1){
                            $totalAmount += $policySpec['explainValue'];
                        }
                    }
                }else{
                    // 一列
                    $policySpec = $policy['policySpec'][0];
                    if($policySpec['explain'] == 1){
                        $totalAmount += $policySpec['explainValue'];
                    }
                }
            }

            $item->totalAmount = $totalAmount;
        }

        return $result;
    }

    // 获取扶贫列表
    protected function getPovertys($where, $start, $length)
    {
        $where['a.isDelete'] = 2;
        $model = new \app\admin\model\Povertyproject();
        $fields = 'a.*';
        $order = 'createDate DESC';
        $result = $model->alias('a')->where($where)->join('member m','a.memberId = m.id')->field($fields)->order($order)->limit($start, $length)->select();
        if(!$result){
            return [];
        }

        foreach ($result as &$item) {
            // 帮扶人 // TODO 不能用 Povertyproject 表里的 aidingId（帮扶人）字段，因为贫困户的 aidingId 会发生改变
            $aidingId = Povertymember::where(['memberId' => $item->memberId])->value('aidingId');
            if($aidingId){
                $aidingInfo = Member::where(['id' => $aidingId])->field('id, name, avatar, job')->find();
                $item->memberaid = $aidingInfo;
            }
        }

        return $result;
    }

    // 获取信息列表
    protected function getDynamics($where, $userId, $start, $length)
    {
        $model = new \app\admin\model\Communitydynamics();
        //$model = db('communitydynamics');
        $fields = 'id, content, createUser as userId, createDate, countComment, countLike';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();

        if($result){
            $result = DynamicService::formatDynamicList($result, $userId);
        }

        return $result;
    }

    /**
     * 享受政策
     */
    public function myPovertypolicy()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->uid)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'uid 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        //$userId = $param->userId;
        $memberId = UserMdl::where(['id' => $param->uid])->value('memberId');
        if(empty($memberId) || !$memberId) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '您还未认证');
        }
        $model = new \app\admin\model\Povertypolicy();
        $result = $this->getPovertypolicys(['memberId' => $memberId], $start, $length);
        $total = $model->alias('a')->where('memberId', $memberId)->join('povertypolicyledger b', 'a.policyledgerId = b.id')->count();

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 享受政策详情
     */
    public function myPovertypolicyDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new \app\admin\model\Povertypolicy();
        $field = '*';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }

        $policyledgerInfo = \app\admin\model\Povertypolicyledger::where(['id' => $item['policyledgerId']])->find();
//        $policyList = json_decode($policyledgerInfo['policy'], true);
        $policyList = json_decode($item['policy'], true);
        $policys = [];
        $policyTotal = 0;
        foreach ($policyList as $policy) {
            foreach ($policy['policySpec'] as $policySpec) {
                $policyName = show_policys($policy['policyType']);
                if ($policySpec['specType'] != 0) {
                    $policyName .= $policyledgerInfo->year . '年';
                    if($policySpec['specType'] == 1){
                        $policyName .= show_quarter($policySpec['quarter']);
                    }else{
                        $policyName .= show_month($policySpec['month']);
                    }
                }

                $policys[] = [
                    'policyType' => $policySpec['explain'],
                    'policyName' => $policyName,
                    'policyValue' => $policySpec['explainValue']
                ];

                if($policySpec['explain'] == 1){
                    $policyTotal += $policySpec['explainValue'];
                }
            }
        }
        // 户主
        $item['householderName'] = Member::where('id', $item['householderId'])->value('name');
        $item['year'] = $policyledgerInfo->year;
        $item['policy'] = $policys;
        $item['policyTotal'] = $policyTotal;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 扶贫
     */
    public function myPoverty()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->uid)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'uid 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        //$userId = $param->userId;
        $memberId = UserMdl::where(['id' => $param->uid])->value('memberId');
        if(empty($memberId) || !$memberId) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '您还未认证为村民');
        }

        // 扶贫项目 // TODO 不能用 Povertyproject 表里的 aidingId（帮扶人）字段，因为贫困户的 aidingId 会发生改变
        //$list = $this->getPovertys(['a.aidingId' => $memberId], $start, $length);
        $memberIds = Povertymember::where(['aidingId' => $memberId])->column('memberId');
        $list = $this->getPovertys(['a.memberId' => ['in', $memberIds]], $start, $length);
        $total = \app\admin\model\Povertyproject::alias('a')->where(['a.memberId' => ['in', $memberIds]])->join('member m','a.memberId = m.id')->count();

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 动态
     */
    public function myDynamics()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'createUser' => $userId,
        ];
        $townId = $param->townId;
        // 动态是否需要审核
        /*$config = $this->getTownConfig($townId);
        if(isset($config['dongtaicheckoff']) && $config['dongtaicheckoff'] == 1){
            $where['isPass'] = 1;
        }*/

        $model = db('communitydynamics');
        $result = $this->getDynamics($where, $userId, $start, $length);
        $total = $model->where($where)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关动态');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 删除动态
     */
    public function delDynamic()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->dynamicsId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'dynamicId 不能为空');
        }

        $dynamicsId = $param->dynamicsId;

        Db::startTrans();
        $model = db('communitydynamics');
        $where = [
            'id' => $dynamicsId
        ];
        $result = $model->where($where)->delete();
        if($result !== false){
            try {
                $dynamicscommentDB = db('articlecomment');
                $dynamicslikeDB = db('articlelike');
                // 删除动态对应的评论
                $dynamicscommentDB->where(['articleId' => $dynamicsId])->delete();
                // 删除点赞
                $dynamicslikeDB->where(['articleId' => $dynamicsId])->delete();
            } catch (Exception $e) {
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败，请稍后再试');
            }
            Db::commit();
        }else{
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败，请稍后再试');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '删除成功');
    }

    /**
     * 关注
     */
    public function myAttention()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'a.userId' => $userId,
        ];

        $model = db('userattention');
        $join = [
            ['__USER__ u', 'a.attentionUserId = u.id'],
        ];
        $fields = 'a.attentionUserId ,u.id as userId, u.nickName, u.avatarUrl';
        $result = $model->alias('a')->where($where)->join($join)->limit($start, $length)->field($fields)->select();
        $total = $model->alias('a')->where($where)->join($join)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到关注');
        }

        foreach ($result as &$item) {
            $countAttentions = $model->where(['attentionUserId' => $item['attentionUserId']])->count();
            // 关注人数
            $item['countAttentions'] = $countAttentions;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 收藏
     */
    public function myCollect()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2, 3, 4, 5])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $type = $param->type;

        $where = [
            'a.userId' => $userId,
        ];
        switch ($type) {
            case 1:
                // 文章
                $result = $this->collectArticle($where, $start, $length);
                break;
            case 2:
                // 产品
                $result = $this->collectProduct($where, $start, $length);
                break;
            case 3:
                // 农事知识
                $result = $this->collectKnowledge($where, $start, $length);
                break;
            case 4:
                // 专题
                $result = $this->collectFeatures($where, $start, $length);
                break;
            case 5:
                // 扶贫工作
                $result = $this->collectPovertywork($where, $start, $length);
                break;
            default : break;
        }

        if(!$result){
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到收藏');
        }

        $list = $result['list'];
        $total = $result['total'];

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }

    /**
     * 文章收藏
     */
    private function collectArticle($where, $start, $length){
        $model = db('usercollect');
        $fields = 'a.id as collectId, b.id as articleId, b.title, b.iconUrl, b.typeId, b.createDate, b.createOper, b.readCount, b.commentCount';
        $list = $model->alias('a')->where($where)->join('__ARTICLE__ b', 'a.collectId = b.id')->limit($start, $length)->field($fields)->select();
        $total = $model->alias('a')->where($where)->join('__ARTICLE__ b', 'a.collectId = b.id')->count();

        if (empty($list)) {
            return [];
        }

        $articletypeDB = db('articletype');
        foreach ($list as &$item) {
            $articleType = $articletypeDB->where(['id' => $item['typeId']])->value('name');
            // 文章类型
            $item['articleType'] = $articleType;
            $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
            if($memberId && $memberId != 0){
                // 组织
                $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
                $item['organization'] = $organization;
            }else{
                $item['organization'] = $this->defaultOrganization;
            }
            unset($item['typeId']);
            unset($item['createOper']);
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 产品收藏
     */
    private function collectProduct($where, $start, $length){
        $model = db('usercollect');
        $fields = 'a.id as collectId, b.id as productId, b.title, b.imgUrl, b.createDate, b.price, b.unit, b.cityId, b.xianId, b.townId, b.villageId, b.preEndTime, b.style';
        $list = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.collectId = b.id')->limit($start, $length)->field($fields)->select();
        $total = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.collectId = b.id')->count();

        if (empty($list)) {
            return [];
        }

        $areaDB = db('area');
        foreach ($list as &$item) {
            $unitArr = get_product_unit();
            $item['unit'] = $unitArr[$item['unit']];
            $city = $areaDB->where(['id' => $item['cityId']])->value('name');
            $xian = $areaDB->where(['id' => $item['xianId']])->value('name');
            $town = $areaDB->where(['id' => $item['townId']])->value('name');
            $village = Villages::where(['id' => $item['villageId']])->value('name');
            $address = $city . $xian . $town . $village;
            // 产地
            $item['address'] = $address;
            unset($item['cityId']);
            unset($item['xianId']);
            unset($item['townId']);
            unset($item['villageId']);
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 农事知识收藏
     */
    private function collectKnowledge($where, $start, $length){
        $model = db('usercollect');
        $fields = 'a.id as collectId, b.id as knowledgeId, b.title, b.imgUrl, b.typeId, b.createDate, b.createOper, b.readCount, b.commentCount';
        $list = $model->alias('a')->where($where)->join('__KNOWLEDGE__ b', 'a.collectId = b.id')->limit($start, $length)->field($fields)->select();
        $total = $model->alias('a')->where($where)->join('__KNOWLEDGE__ b', 'a.collectId = b.id')->count();

        if (empty($list)) {
            return [];
        }

        foreach ($list as &$item) {
            $item['typeId'] = \app\admin\model\Knowledgetype::where('id', $item['typeId'])->value('name');
            $item['imgUrl'] = $item['imgUrl'].'?imageView2/1/w/330/h/220';
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 专题收藏
     */
    private function collectFeatures($where, $start, $length){
        $model = db('usercollect');
        $fields = 'a.id as collectId, b.id as featuresId, b.title, b.imgUrl, b.typeId, b.createDate, b.createOper, b.description, b.readCount, b.commentCount';
        $list = $model->alias('a')->where($where)->join('__FEATURES__ b', 'a.collectId = b.id')->limit($start, $length)->field($fields)->select();
        $total = $model->alias('a')->where($where)->join('__FEATURES__ b', 'a.collectId = b.id')->count();

        if (empty($list)) {
            return [];
        }

        $featurecolumnDB = db('featurecolumn');
        foreach ($list as &$item) {
            $memberId = Operator::where(['id' => $item['createOper']])->value('memberId');
            if($memberId && $memberId != 0){
                // 组织
                $organization = Member::alias('a')->where(['a.id' => $memberId])->join('__ORGANIZATION__ o', 'a.organizationId = o.id')->value('o.name');
                $item['organization'] = $organization;
            }else{
                $item['organization'] = $this->defaultOrganization;
            }
            unset($item['createOper']);

            $item['typeName'] = $featurecolumnDB->where(['id' => $item['typeId']])->field('name')->value('name');
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 扶贫工作收藏
     */
    private function collectPovertywork($where, $start, $length){
        $model = db('usercollect');
        $fields = 'a.id as collectId, b.id as povertyworkId, b.povertymemberId, b.povertypartyId, b.content, b.createDate, b.createOper, b.readCount, b.commentCount';
        $list = $model->alias('a')->where($where)->join('__POVERTYWORK__ b', 'a.collectId = b.id')->limit($start, $length)->field($fields)->select();
        $total = $model->alias('a')->where($where)->join('__POVERTYWORK__ b', 'a.collectId = b.id')->count();

        if (empty($list)) {
            return [];
        }

        foreach ($list as &$item) {
            // 贫困户基本信息
            $item['member'] = Member::where('id', $item['povertymemberId'])->field('name, avatar')->find();
            // 帮扶人信息
            $item['memberaid'] = Member::where('id', $item['povertypartyId'])->field('name, avatar')->find();
            // 图集
            $item['imgList'] = Image::where(['relatedId' => $item['povertyworkId'], 'tag' => 'imglist'])->field('imgUrl')->select();
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 发布留言
     */
    public function postMessage()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->content) || !trim($param->content)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '留言内容不能为空');
        }

        $userId = $param->userId;
        $areaIds = $this->getParentIdsByTownId($param->townId);

        Db::startTrans();
        try {
            $model = db('messages');
            $data = [
                'id' => BaseHelper::getUUID(),
                'createDate' => time(),
                'cityId' => $areaIds['cityId'],
                'xianId' => $areaIds['xianId'],
                'townId' => $param->townId,
                'userId' => $userId,
                'content' => $param->content,
            ];
            $result = $model->insert($data);

            if($result !== false){
                // 图片
                $res = '';
                if(isset($param->imgUrls) && $param->imgUrls) {
                    $imgUrls = (array) $param->imgUrls;
                    foreach($imgUrls as $key => $imgUrl){
                        $res = Image::where(['imgUrl' => $imgUrl])->update(['relatedId' => $data['id'], 'controller' => 'Messages', 'relatedTable' => 'messages', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '发布留言失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '发布留言失败', $e->getMessage());
        }
    }
}